package nl.hu.vakantievibes.ui;


import nl.hu.vakantievibes.client.FieldVerifier;
import nl.hu.vakantievibes.client.Systeem;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Inloggen {
	
	Label lblNaam = new Label("Gebruikersnaam:");
	TextBox txtNaam = new TextBox();
	Label lblWachtwoord = new Label("Wachtwoord:");
	PasswordTextBox pwdWachtwoord = new PasswordTextBox();
	Button btnOk = new Button("Inloggen");
	Button btnCancel = new Button("Reset");
	
	public Inloggen() {
		if(!Systeem.get().loggedIn()) {
			loginField();
		} else {
			History.newItem("allereizen");
		}
	}
	
	public void loginField() {
		btnOk.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				handleFields();			
			}
		});
		
		KeyPressHandler loginKeyHandler = new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				if(event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
					handleFields();
				}			
			}
		};
		
		txtNaam.addKeyPressHandler(loginKeyHandler);
		pwdWachtwoord.addKeyPressHandler(loginKeyHandler);
		
		btnCancel.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				resetFields();
			}
		});	
	}
	
	public Panel createPage() {
		VerticalPanel vp = new VerticalPanel();
		vp.add(lblNaam); vp.add(txtNaam);
		vp.add(lblWachtwoord);vp.add(pwdWachtwoord);
		HorizontalPanel buttonPanel = new HorizontalPanel();
		buttonPanel.add(btnOk); buttonPanel.add(btnCancel);
		vp.add(buttonPanel); 
		return vp;
	}
	
	private void handleFields() {
		int b = 0;
		if (txtNaam.getText().matches("^[A-Za-z-0-9]+$") &&
			FieldVerifier.get().checkField(txtNaam.getText(), 4, 30)) {
			txtNaam.setStyleName("green-border");
			b += 1;
		} else {
			txtNaam.setStyleName("red-border");
		}
		
		if (FieldVerifier.get().checkField(pwdWachtwoord.getText(), 4, 30)) {
			pwdWachtwoord.setStyleName("green-border");
			b += 1;
		} else {
			pwdWachtwoord.setStyleName("red-border");
		}
		
		if(b == 2) {
			FieldVerifier.get().checkLogin(txtNaam, pwdWachtwoord);
		}
	}
	
	private void resetFields() {
		txtNaam.setText(""); txtNaam.setStyleName("");
		pwdWachtwoord.setText(""); pwdWachtwoord.setStyleName("");
	}
}